// 简单的Express后端服务
const express = require('express');
const cors = require('cors');
const multer = require('multer');

const fs = require('fs');
const path = require('path');
const database = require('../src/config/database');
const pool = database.default || database.pool;

// 创建testConnection函数
const testConnection = async () => {
  try {
    const client = await pool.connect();
    const result = await client.query('SELECT NOW()');
    console.log('🔗 数据库连接测试成功:', result.rows[0]);
    client.release();
    return true;
  } catch (error) {
    console.error('❌ 数据库连接测试失败:', error);
    return false;
  }
};
const authService = require('./services/authService');
const articleService = require('./services/articleService');
const documentConversionService = require('./services/documentConversionService');
const pdfConversionService = require('./services/pdfConversionService');

const app = express();
const PORT = process.env.PORT || 9091;

// 中间件
app.use(cors());
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ extended: true, limit: '100mb' }));

// 文件上传配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = 'uploads/';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 100 * 1024 * 1024 // 100MB限制
  },
  fileFilter: (req, file, cb) => {
    // 修复中文文件名编码问题
    if (file.originalname) {
      try {
        // 检测是否需要编码转换
        const decoded = decodeURIComponent(escape(file.originalname));
        if (decoded !== file.originalname) {
          file.originalname = decoded;
        }
      } catch (e) {
        // 如果解码失败，尝试Buffer转换
        try {
          file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf8');
        } catch (e2) {
          console.warn('文件名编码转换失败:', file.originalname);
        }
      }
    }
    const allowedTypes = [
      // 文档类型
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
      'application/msword', // .doc
      'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
      'application/vnd.ms-powerpoint', // .ppt
      'application/pdf', // .pdf
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
      'application/vnd.ms-excel', // .xls
      'text/plain', // .txt
      // 图片类型
      'image/jpeg',
      'image/jpg',
      'image/png',
      'image/gif',
      'image/webp',
      'image/svg+xml'
    ];
    
    // 也可以根据文件扩展名判断
    const allowedExtensions = ['.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx', '.txt', 
                              '.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg'];
    const fileExtension = path.extname(file.originalname).toLowerCase();
    
    if (allowedTypes.includes(file.mimetype) || allowedExtensions.includes(fileExtension)) {
      cb(null, true);
    } else {
      cb(new Error(`不支持的文件类型: ${file.mimetype} (${fileExtension})`), false);
    }
  }
});



// 认证中间件
const authenticateToken = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问令牌缺失'
      });
    }

    // 检查token格式
    if (!token || token === 'null' || token === 'undefined') {
      return res.status(401).json({
        success: false,
        message: 'Token格式无效'
      });
    }

    const result = await authService.verifyToken(token);
    if (!result.success) {
      return res.status(401).json({
        success: false,
        message: result.message || 'Token验证失败'
      });
    }

    req.user = result.data;
    next();
  } catch (error) {
    console.error('认证中间件错误:', error);
    return res.status(401).json({
      success: false,
      message: '认证失败'
    });
  }
};

// 用户认证相关API
app.post('/api/auth/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    console.log('[后端] 收到登录请求:', { email, password: '***' });
    
    if (!email || !password) {
      return res.status(400).json({
        success: false,
        message: '请填写邮箱和密码'
      });
    }
    
    const result = await authService.login({ email, password });
    
    if (result.success) {
      console.log('[后端] 登录成功:', result.data.user.email);
      res.json(result);
    } else {
      console.log('[后端] 登录失败:', result.message);
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('[后端] 登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 管理员登录API
app.post('/api/auth/admin-login', async (req, res) => {
  try {
    const { email, password } = req.body;
    console.log('[后端] 收到管理员登录请求:', { email, password: '***' });
    
    if (!email || !password) {
      return res.status(400).json({
        success: false,
        message: '请填写邮箱和密码'
      });
    }
    
    const result = await authService.adminLogin({ email, password });
    
    if (result.success) {
      console.log('[后端] 管理员登录成功:', result.data.user.email);
      res.json(result);
    } else {
      console.log('[后端] 管理员登录失败:', result.message);
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('[后端] 管理员登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

app.post('/api/auth/register', async (req, res) => {
  try {
    const { username, email, password } = req.body;
    console.log('[后端] 收到注册请求:', { username, email, password: '***' });
    
    if (!username || !email || !password) {
      return res.status(400).json({
        success: false,
        message: '请填写完整信息'
      });
    }
    
    if (password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '密码长度至少6位'
      });
    }
    
    const result = await authService.register({ username, email, password });
    
    if (result.success) {
      console.log('[后端] 注册成功:', result.data.user.email);
      res.json(result);
    } else {
      console.log('[后端] 注册失败:', result.message);
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('[后端] 注册错误:', error);
    res.status(500).json({
      success: false,
      message: '注册失败'
    });
  }
});

app.get('/api/auth/me', authenticateToken, (req, res) => {
  res.json({
    success: true,
    data: req.user
  });
});

// 作品相关API
app.get('/api/articles', async (req, res) => {
  try {
    console.log('[后端] 收到获取作品列表请求:', req.query);
    const { page, limit, status, search, user_id } = req.query;
    
    const options = {
      page: parseInt(page) || 1,
      limit: parseInt(limit) || 10,
      status: status || 'published',
      search,
      user_id: user_id ? parseInt(user_id) : undefined
    };
    
    console.log('[后端] 查询参数:', options);
    
    // 尝试从数据库获取数据，如果失败则使用模拟数据
    let result;
    try {
      result = await articleService.getArticles(options);
      console.log('[后端] 数据库查询结果:', result.success ? '成功' : '失败', result.message || '');
    } catch (dbError) {
      console.log('[后端] 数据库查询失败，使用模拟数据:', dbError.message);
      // 使用模拟数据
      const mockArticles = [
        {
          id: 1,
          title: '示例作品1',
          content_html: '<p>这是一篇示例作品的内容...</p>',
          cover_image: null,
          status: 'published',
          view_count: 120,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
          username: '示例用户',
          avatar_url: null
        },
        {
          id: 2,
          title: '示例作品2',
          content_html: '<p>这是另一篇示例作品的内容...</p>',
          cover_image: null,
          status: 'published',
          view_count: 85,
          created_at: new Date(Date.now() - 86400000).toISOString(),
          updated_at: new Date(Date.now() - 86400000).toISOString(),
          username: '示例用户',
          avatar_url: null
        }
      ];
      
      result = {
        success: true,
        data: {
          articles: mockArticles,
          pagination: {
            page: options.page,
            limit: options.limit,
            total: mockArticles.length,
            totalPages: 1
          }
        }
      };
    }
    
    if (result.success) {
      res.json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('[后端] 获取作品列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取作品列表失败'
    });
  }
});

app.post('/api/articles', authenticateToken, async (req, res) => {
  try {
    const { title, description, content, content_html, cover_image, status } = req.body;
    console.log('[后端] 收到创建作品请求:', { title, status });
    
    if (!title || !content_html) {
      return res.status(400).json({
        success: false,
        message: '标题和内容不能为空'
      });
    }
    
    const articleData = {
      user_id: req.user.id,
      title,
      description,
      content,
      content_html,
      cover_image,
      status: status || 'published'
    };
    
    const result = await articleService.createArticle(articleData);
    
    if (result.success) {
      console.log('[后端] 作品创建成功:', result.data.id);
      res.json(result);
    } else {
      console.log('[后端] 作品创建失败:', result.message);
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('[后端] 创建作品错误:', error);
    res.status(500).json({
      success: false,
      message: '创建作品失败'
    });
  }
});

app.get('/api/articles/:id', async (req, res) => {
  try {
    const articleId = parseInt(req.params.id);
    
    if (!articleId) {
      return res.status(400).json({
        success: false,
        message: '无效的作品ID'
      });
    }
    
    const result = await articleService.getArticleById(articleId);
    
    if (result.success) {
      // 增加浏览量
      await articleService.incrementViewCount(articleId);
      res.json(result);
    } else {
      res.status(404).json(result);
    }
  } catch (error) {
    console.error('[后端] 获取作品详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取作品详情失败'
    });
  }
});

// 获取作品附件列表
app.get('/api/articles/:id/attachments', async (req, res) => {
  try {
    const articleId = parseInt(req.params.id);
    
    if (!articleId) {
      return res.status(400).json({
        success: false,
        message: '无效的作品ID'
      });
    }
    
    const result = await articleService.getArticleAttachments(articleId);
    res.json(result);
  } catch (error) {
    console.error('[后端] 获取附件列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取附件列表失败'
    });
  }
});

// 删除附件
app.delete('/api/attachments/:id', authenticateToken, async (req, res) => {
  try {
    const attachmentId = parseInt(req.params.id);
    const userId = req.user.id;
    
    if (!attachmentId) {
      return res.status(400).json({
        success: false,
        message: '无效的附件ID'
      });
    }
    
    const result = await articleService.deleteAttachment(attachmentId, userId);
    res.json(result);
  } catch (error) {
    console.error('[后端] 删除附件错误:', error);
    res.status(500).json({
      success: false,
      message: '删除附件失败'
    });
  }
});

// 删除媒体文件（兼容性API）
app.delete('/api/media-files/:id', authenticateToken, async (req, res) => {
  try {
    const fileId = parseInt(req.params.id);
    const userId = req.user.id;
    
    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      });
    }
    
    const result = await articleService.deleteAttachment(fileId, userId);
    res.json(result);
  } catch (error) {
    console.error('[后端] 删除媒体文件错误:', error);
    res.status(500).json({
      success: false,
      message: '删除媒体文件失败'
    });
  }
});

// 添加附件到作品
app.post('/api/articles/:id/attachments', authenticateToken, async (req, res) => {
  try {
    const articleId = parseInt(req.params.id);
    const userId = req.user.id;
    const attachmentData = req.body;
    
    if (!articleId) {
      return res.status(400).json({
        success: false,
        message: '无效的作品ID'
      });
    }
    
    const result = await articleService.addAttachment(articleId, userId, attachmentData);
    res.json(result);
  } catch (error) {
    console.error('[后端] 添加附件错误:', error);
    res.status(500).json({
      success: false,
      message: '添加附件失败'
    });
  }
});

app.put('/api/articles/:id', authenticateToken, async (req, res) => {
  try {
    const articleId = parseInt(req.params.id);
    const { title, description, content, content_html, cover_image, status } = req.body;
    
    if (!articleId) {
      return res.status(400).json({
        success: false,
        message: '无效的作品ID'
      });
    }
    
    if (!title || !content_html) {
      return res.status(400).json({
        success: false,
        message: '标题和内容不能为空'
      });
    }
    
    const articleData = {
      title,
      description,
      content,
      content_html,
      cover_image,
      status: status || 'published'
    };
    
    const result = await articleService.updateArticle(articleId, req.user.id, articleData);
    
    if (result.success) {
      console.log('[后端] 作品更新成功:', articleId);
      res.json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('[后端] 更新作品错误:', error);
    res.status(500).json({
      success: false,
      message: '更新作品失败'
    });
  }
});

app.delete('/api/articles/:id', authenticateToken, async (req, res) => {
  try {
    const articleId = parseInt(req.params.id);
    
    if (!articleId) {
      return res.status(400).json({
        success: false,
        message: '无效的作品ID'
      });
    }
    
    const result = await articleService.deleteArticle(articleId, req.user.id);
    
    if (result.success) {
      console.log('[后端] 作品删除成功:', articleId);
      res.json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('[后端] 删除作品错误:', error);
    res.status(500).json({
      success: false,
      message: '删除作品失败'
    });
  }
});

// 统计数据API
app.get('/api/stats', async (req, res) => {
  try {
    console.log('[后端] 获取统计数据请求');
    
    // 尝试从数据库获取数据，如果失败则使用模拟数据
    let stats;
    try {
      // 获取总作品数
      const articlesResult = await pool.query(`
        SELECT COUNT(*) as total_articles FROM articles WHERE status = 'published'
      `);
      
      // 获取总浏览量
      const viewsResult = await pool.query(`
        SELECT SUM(view_count) as total_views FROM articles WHERE status = 'published'
      `);
      
      stats = {
        totalArticles: parseInt(articlesResult.rows[0].total_articles) || 0,
        totalViews: parseInt(viewsResult.rows[0].total_views) || 0
      };
    } catch (dbError) {
      console.log('[后端] 数据库查询失败，使用模拟数据:', dbError.message);
      // 使用模拟数据
      stats = {
        totalArticles: 5,
        totalViews: 1250
      };
    }
    
    console.log('[后端] 统计数据:', stats);
    
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    console.error('[后端] 获取统计数据错误:', error);
    res.status(500).json({
      success: false,
      message: '获取统计数据失败'
    });
  }
});

// 文件上传API
app.post('/api/upload/image', authenticateToken, (req, res) => {
  upload.single('file')(req, res, (err) => {
    if (err) {
      console.error('文件上传错误:', err);
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.status(413).json({
          success: false,
          message: '文件大小超过限制（最大100MB）'
        });
      }
      return res.status(400).json({
        success: false,
        message: err.message || '文件上传失败'
      });
    }

    try {
      if (!req.file) {
        return res.status(400).json({
          success: false,
          message: '没有上传文件'
        });
      }

      const fileUrl = `/uploads/${req.file.filename}`;
      
      res.json({
        success: true,
        data: {
          url: fileUrl,
          filename: req.file.filename,
          originalName: req.file.originalname,
          size: req.file.size
        }
      });
    } catch (error) {
      console.error('图片上传错误:', error);
      res.status(500).json({
        success: false,
        message: '图片上传失败'
      });
    }
  });
});

app.post('/api/upload/document', authenticateToken, (req, res) => {
  upload.single('file')(req, res, async (err) => {
    if (err) {
      console.error('文件上传错误:', err);
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.status(413).json({
          success: false,
          message: '文件大小超过限制（最大100MB）'
        });
      }
      return res.status(400).json({
        success: false,
        message: err.message || '文件上传失败'
      });
    }

    try {
      if (!req.file) {
        return res.status(400).json({
          success: false,
          message: '没有上传文件'
        });
      }

      const fileUrl = `/uploads/${req.file.filename}`;
      const filePath = req.file.path;
      
      // 如果是Office文档，尝试转换为HTML和PDF
      let conversionResult = null;
      let pdfConversionResult = null;
      
      const isOfficeDocument = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-powerpoint',
        'application/pdf',
        'text/plain'
      ].includes(req.file.mimetype);

      const isPdfConvertible = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-powerpoint'
      ].includes(req.file.mimetype);

      if (isOfficeDocument) {
        console.log('检测到Office文档，开始HTML转换:', req.file.originalname);
        conversionResult = await documentConversionService.convertDocument(
          filePath, 
          req.file.originalname, 
          req.file.mimetype
        );
        
        if (conversionResult.success) {
          console.log('HTML转换成功');
        } else {
          console.log('HTML转换失败:', conversionResult.error);
        }
      }

      // 对Word和PPT文档进行PDF转换
      if (isPdfConvertible) {
        console.log('检测到可转PDF文档，开始PDF转换:', req.file.originalname);
        pdfConversionResult = await pdfConversionService.convertToPdf(
          filePath,
          req.file.originalname,
          req.file.mimetype
        );
        
        if (pdfConversionResult.success) {
          console.log('PDF转换成功:', pdfConversionResult.pdfFileName);
        } else {
          console.log('PDF转换失败:', pdfConversionResult.error);
        }
      }

      // 检查是否需要立即保存到数据库
      const { article_id, immediate_save } = req.body;
      let fileId = null;
      
      if (immediate_save === 'true' && article_id) {
        console.log('立即保存模式，保存文件到数据库...');
        
        // 保存文件记录到数据库
        const fileData = {
          file_name: req.file.filename,
          original_name: req.file.originalname,
          file_type: 'document',
          file_size: req.file.size,
          file_url: fileUrl,
          mime_type: req.file.mimetype
        };

        const fileResult = await articleService.addAttachment(article_id, req.user.id, fileData);
        
        if (fileResult.success) {
          fileId = fileResult.data.id;
          console.log('文件记录保存成功，ID:', fileId);
          
          // 如果有PDF转换结果，保存到数据库
          if (pdfConversionResult && pdfConversionResult.success) {
            const pdfSaveResult = await pdfConversionService.savePdfConversionResult(
              req.user.id,
              fileId,
              pdfConversionResult.pdfPath,
              pdfConversionResult.pdfUrl,
              pdfConversionResult.isPlaceholder ? 'placeholder' : 'completed'
            );
            
            if (pdfSaveResult.success) {
              console.log('PDF转换信息保存成功');
            } else {
              console.error('PDF转换信息保存失败:', pdfSaveResult.error);
            }
          } else if (pdfConversionResult && !pdfConversionResult.success) {
            // 保存失败记录
            await pdfConversionService.savePdfConversionResult(
              req.user.id,
              fileId,
              '',
              '',
              'failed',
              pdfConversionResult.error
            );
          }
        } else {
          console.error('文件记录保存失败:', fileResult.message);
        }
      }
      
      res.json({
        success: true,
        data: {
          id: fileId,
          url: fileUrl,
          filename: req.file.filename,
          originalName: req.file.originalname,
          size: req.file.size,
          type: req.file.mimetype,
          conversion: conversionResult,
          pdfConversion: pdfConversionResult,
          // 返回PDF状态信息
          pdf_status: pdfConversionResult ? 
            (pdfConversionResult.success ? 
              (pdfConversionResult.isPlaceholder ? 'placeholder' : 'completed') 
              : 'failed') 
            : 'unknown',
          pdf_url: pdfConversionResult && pdfConversionResult.success ? pdfConversionResult.pdfUrl : null
        }
      });
    } catch (error) {
      console.error('文档上传错误:', error);
      res.status(500).json({
        success: false,
        message: '文档上传失败'
      });
    }
  });
});

// 上传文档并立即保存到数据库（包含PDF转换）
app.post('/api/upload/document-with-save', authenticateToken, (req, res) => {
  upload.single('file')(req, res, async (err) => {
    if (err) {
      console.error('文件上传错误:', err);
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.status(413).json({
          success: false,
          message: '文件大小超过限制（最大100MB）'
        });
      }
      return res.status(400).json({
        success: false,
        message: err.message || '文件上传失败'
      });
    }

    try {
      if (!req.file) {
        return res.status(400).json({
          success: false,
          message: '没有上传文件'
        });
      }

      const { article_id } = req.body;
      if (!article_id) {
        return res.status(400).json({
          success: false,
          message: '缺少作品ID'
        });
      }

      const fileUrl = `/uploads/${req.file.filename}`;
      const filePath = req.file.path;
      const userId = req.user.id;
      
      // 1. 先保存文件记录到数据库
      const fileData = {
        file_name: req.file.filename,
        original_name: req.file.originalname,
        file_type: 'document',
        file_size: req.file.size,
        file_url: fileUrl,
        mime_type: req.file.mimetype
      };

      const fileResult = await articleService.addAttachment(article_id, userId, fileData);
      
      if (!fileResult.success) {
        return res.status(400).json({
          success: false,
          message: '保存文件记录失败: ' + fileResult.message
        });
      }

      const fileId = fileResult.data.id;
      console.log('文件记录保存成功，ID:', fileId);

      // 2. 进行PDF转换
      let pdfConversionResult = null;
      const isPdfConvertible = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-powerpoint'
      ].includes(req.file.mimetype);

      if (isPdfConvertible) {
        console.log('检测到可转PDF文档，开始PDF转换:', req.file.originalname);
        pdfConversionResult = await pdfConversionService.convertToPdf(
          filePath,
          req.file.originalname,
          req.file.mimetype
        );
        
        if (pdfConversionResult.success) {
          console.log('PDF转换成功:', pdfConversionResult.pdfFileName);
          
          // 3. 保存PDF转换结果到数据库
          const pdfSaveResult = await pdfConversionService.savePdfConversionResult(
            userId,
            fileId,
            pdfConversionResult.pdfPath,
            pdfConversionResult.pdfUrl,
            pdfConversionResult.isPlaceholder ? 'placeholder' : 'completed'
          );
          
          if (pdfSaveResult.success) {
            console.log('PDF转换信息保存成功');
          } else {
            console.error('PDF转换信息保存失败:', pdfSaveResult.error);
          }
        } else {
          console.log('PDF转换失败:', pdfConversionResult.error);
          
          // 保存失败记录
          await pdfConversionService.savePdfConversionResult(
            userId,
            fileId,
            '',
            '',
            'failed',
            pdfConversionResult.error
          );
        }
      }
      
      res.json({
        success: true,
        data: {
          id: fileId,
          url: fileUrl,
          filename: req.file.filename,
          originalName: req.file.originalname,
          size: req.file.size,
          type: req.file.mimetype,
          pdfConversion: pdfConversionResult,
          // 返回PDF状态信息
          pdf_status: pdfConversionResult ? 
            (pdfConversionResult.success ? 
              (pdfConversionResult.isPlaceholder ? 'placeholder' : 'completed') 
              : 'failed') 
            : 'unknown',
          pdf_url: pdfConversionResult && pdfConversionResult.success ? pdfConversionResult.pdfUrl : null
        }
      });
    } catch (error) {
      console.error('文档上传和保存错误:', error);
      res.status(500).json({
        success: false,
        message: '文档上传和保存失败'
      });
    }
  });
});

// 保存PDF转换信息
app.post('/api/pdf-conversions', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { original_file_id, pdf_url, pdf_path, conversion_status } = req.body;
    
    if (!original_file_id || !pdf_url) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }

    const result = await pdfConversionService.savePdfConversionResult(
      userId, 
      original_file_id, 
      pdf_path, 
      pdf_url, 
      conversion_status || 'completed'
    );
    
    res.json(result);
  } catch (error) {
    console.error('保存PDF转换信息失败:', error);
    res.status(500).json({
      success: false,
      message: '保存PDF转换信息失败'
    });
  }
});

// 获取附件的PDF版本
app.get('/api/attachments/:id/pdf', async (req, res) => {
  try {
    const attachmentId = parseInt(req.params.id);
    
    if (!attachmentId) {
      return res.status(400).json({
        success: false,
        message: '无效的附件ID'
      });
    }

    // 查询附件信息和PDF转换结果（先尝试media_files表）
    let query = `
      SELECT 
        a.*,
        pc.pdf_url,
        pc.pdf_path,
        pc.conversion_status as pdf_status
      FROM media_files a
      LEFT JOIN pdf_conversions pc ON a.id = pc.original_file_id
      WHERE a.id = $1
    `;
    
    let result = await pool.query(query, [attachmentId]);
    
    // 如果media_files表中没有，尝试attachments表（向后兼容）
    if (result.rows.length === 0) {
      query = `
        SELECT 
          a.*,
          pc.pdf_url,
          pc.pdf_path,
          pc.conversion_status as pdf_status
        FROM attachments a
        LEFT JOIN pdf_conversions pc ON a.id = pc.original_file_id
        WHERE a.id = $1
      `;
      
      try {
        result = await pool.query(query, [attachmentId]);
      } catch (error) {
        // attachments表不存在，忽略错误
      }
    }
    
    if (result.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '附件不存在'
      });
    }

    const attachment = result.rows[0];
    
    if (attachment.pdf_url && (attachment.pdf_status === 'completed' || attachment.pdf_status === 'placeholder')) {
      res.json({
        success: true,
        data: {
          pdf_url: attachment.pdf_url,
          pdf_path: attachment.pdf_path,
          original_name: attachment.original_name,
          mime_type: attachment.mime_type,
          is_placeholder: attachment.pdf_status === 'placeholder'
        }
      });
    } else {
      res.status(404).json({
        success: false,
        message: 'PDF版本不存在或转换未完成'
      });
    }
  } catch (error) {
    console.error('获取PDF版本失败:', error);
    res.status(500).json({
      success: false,
      message: '获取PDF版本失败'
    });
  }
});

// 获取文档转换结果
app.get('/api/documents/:id/conversion', async (req, res) => {
  try {
    const fileId = parseInt(req.params.id);
    
    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      });
    }
    
    const result = await documentConversionService.getConversionResult(fileId);
    res.json(result);
  } catch (error) {
    console.error('获取文档转换结果错误:', error);
    res.status(500).json({
      success: false,
      message: '获取转换结果失败'
    });
  }
});

// 获取PDF转换结果
app.get('/api/documents/:id/pdf', async (req, res) => {
  try {
    const fileId = parseInt(req.params.id);
    
    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      });
    }
    
    const result = await pdfConversionService.getPdfConversionResult(fileId);
    res.json(result);
  } catch (error) {
    console.error('获取PDF转换结果错误:', error);
    res.status(500).json({
      success: false,
      message: '获取PDF转换结果失败'
    });
  }
});

// 检查PDF转换状态
app.get('/api/pdf-conversions/status/:fileId', async (req, res) => {
  try {
    const fileId = parseInt(req.params.fileId);
    
    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      });
    }
    
    const result = await pdfConversionService.getPdfConversionResult(fileId);
    res.json(result);
  } catch (error) {
    console.error('检查PDF转换状态错误:', error);
    res.status(500).json({
      success: false,
      message: '检查PDF转换状态失败'
    });
  }
});

// 转换文档为PDF (允许访客访问)
app.post('/api/documents/:id/convert-pdf', async (req, res) => {
  try {
    const fileId = parseInt(req.params.id);
    
    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      });
    }
    
    // 先尝试从media_files表获取文件信息
    let fileQuery = `
      SELECT * FROM media_files 
      WHERE id = $1
    `;
    
    let fileResult = await pool.query(fileQuery, [fileId]);
    
    // 如果media_files表中没有，再尝试attachments表（向后兼容）
    if (fileResult.rows.length === 0) {
      fileQuery = `
        SELECT * FROM attachments 
        WHERE id = $1
      `;
      try {
        fileResult = await pool.query(fileQuery, [fileId]);
      } catch (error) {
        // attachments表不存在，忽略错误
      }
    }
    
    if (fileResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '文件不存在'
      });
    }
    
    const file = fileResult.rows[0];
    const filePath = path.join(process.cwd(), 'uploads', file.file_name);
    
    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        message: '文件不存在'
      });
    }
    
    // 转换为PDF
    const pdfResult = await pdfConversionService.convertToPdf(
      filePath,
      file.original_name,
      file.mime_type
    );
    
    if (pdfResult.success) {
      // 保存转换结果到数据库
      await pdfConversionService.savePdfConversionResult(
        file.user_id,
        fileId,
        pdfResult.pdfPath,
        pdfResult.pdfUrl,
        'completed'
      );
      
      res.json({
        success: true,
        data: {
          pdfUrl: pdfResult.pdfUrl,
          pdfFileName: pdfResult.pdfFileName,
          isPlaceholder: pdfResult.isPlaceholder || false,
          isOriginalPdf: pdfResult.isOriginalPdf || false,
          originalSize: pdfResult.originalSize,
          pdfSize: pdfResult.pdfSize
        }
      });
    } else {
      // 保存错误信息到数据库
      await pdfConversionService.savePdfConversionResult(
        file.user_id,
        fileId,
        '',
        '',
        'failed',
        pdfResult.error
      );
      
      res.status(400).json({
        success: false,
        message: pdfResult.error
      });
    }
  } catch (error) {
    console.error('PDF转换错误:', error);
    res.status(500).json({
      success: false,
      message: 'PDF转换失败'
    });
  }
});

// 转换文档为HTML (允许访客访问)
app.post('/api/documents/:id/convert', async (req, res) => {
  try {
    const fileId = parseInt(req.params.id);
    
    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      });
    }
    
    // 先尝试从media_files表获取文件信息
    let fileQuery = `
      SELECT * FROM media_files 
      WHERE id = $1
    `;
    
    let fileResult = await pool.query(fileQuery, [fileId]);
    
    // 如果media_files表中没有，再尝试attachments表（向后兼容）
    if (fileResult.rows.length === 0) {
      fileQuery = `
        SELECT * FROM attachments 
        WHERE id = $1
      `;
      try {
        fileResult = await pool.query(fileQuery, [fileId]);
      } catch (error) {
        // attachments表不存在，忽略错误
      }
    }
    
    if (fileResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '文件不存在或无权限访问'
      });
    }
    
    const file = fileResult.rows[0];
    const filePath = path.join(process.cwd(), 'uploads', file.file_name);
    
    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        message: '文件不存在'
      });
    }
    
    // 转换文档
    const conversionResult = await documentConversionService.convertDocument(
      filePath,
      file.original_name,
      file.mime_type
    );
    
    if (conversionResult.success) {
      // 保存转换结果到数据库 (使用文件所有者ID)
      await documentConversionService.saveConversionResult(
        file.user_id,
        fileId,
        conversionResult.html,
        'completed'
      );
      
      res.json({
        success: true,
        data: {
          html: conversionResult.html,
          isPreview: conversionResult.isPreview || false,
          isEmbedded: conversionResult.isEmbedded || false,
          warnings: conversionResult.warnings || []
        }
      });
    } else {
      // 保存错误信息到数据库 (使用文件所有者ID)
      await documentConversionService.saveConversionResult(
        file.user_id,
        fileId,
        '',
        'failed',
        conversionResult.error
      );
      
      res.status(400).json({
        success: false,
        message: conversionResult.error
      });
    }
  } catch (error) {
    console.error('文档转换错误:', error);
    res.status(500).json({
      success: false,
      message: '文档转换失败'
    });
  }
});

// 静态文件服务
app.use('/uploads', express.static('uploads'));

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'OK', 
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  });
});

// 测试API路由
app.get('/api/test', (req, res) => {
  console.log('[后端] 收到测试请求');
  res.json({
    success: true,
    message: 'API路由正常工作',
    timestamp: new Date().toISOString()
  });
});

// 创建测试用户 (仅用于开发测试)
app.post('/api/test/create-user', async (req, res) => {
  try {
    const testUser = {
      username: 'testuser',
      email: 'test@example.com',
      password: 'test123'
    };

    const result = await authService.register(testUser);
    
    if (result.success) {
      console.log('[测试] 测试用户创建成功');
      res.json({
        success: true,
        message: '测试用户创建成功',
        data: result.data
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    console.error('[测试] 创建测试用户失败:', error);
    res.status(500).json({
      success: false,
      message: '创建测试用户失败'
    });
  }
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: error.message || '服务器内部错误'
  });
});

// 启动服务器
app.listen(PORT, async (err) => {
  if (err) {
    console.error('❌ 服务器启动失败:', err);
    process.exit(1);
  }
  
  console.log('🚀 服务器启动成功!');
  console.log(`📍 端口: ${PORT}`);
  console.log(`📊 健康检查: http://211.86.197.10:${PORT}/api/health`);
  console.log(`🔐 登录API: http://211.86.197.10:${PORT}/api/auth/login`);

  
  // 测试数据库连接
  console.log('🔗 正在测试数据库连接...');
  const dbConnected = await testConnection();
  
  if (dbConnected) {
    console.log('✅ 数据库连接正常，服务器就绪');
  } else {
    console.log('⚠️  数据库连接失败，但服务器仍可运行');
  }
  
  console.log('✅ 服务器就绪，等待请求...');
});

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  console.error('❌ 未捕获的异常:', err);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('❌ 未处理的Promise拒绝:', reason);
  process.exit(1);
});